<template>
  <a-modal
    :title="pop.title"
    :visible="visible"
    :maskClosable="false"
    :width="pop.width"
    @cancel="close"
    @ok="onPopSubmit"
    :confirmLoading="pop.loading"
  >
    <div class="ctr-box" style="z-index: 100;height: 50px;position: relative;">
      <a-form-model
        ref="ruleForm"
        :form="editForm"
        :model="editForm"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="区域名称" prop="sysAreaId">
          <a-select
            style="width: 100%;"
            placeholder="请选择区域名称"
            v-model="editForm.sysAreaId"
            @change="onAreaChange"
            :disabled="isStatus == 'view'"
          >
            <a-select-option v-for="(item, index) in areaList" :key="index" :value="item.id">{{
              item.name
            }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="大屏监控" prop="deviceIds" style="margin-left:20px;">
          <a-select
            :disabled="isStatus == 'view'"
            style="width: 100%;"
            mode="multiple"
            placeholder="请选择大屏监控"
            v-model="editForm.deviceIds"
            @change="onCameraChange"
          >
            <a-select-option v-for="(item, index) in camerasList" :key="index" :value="item.id">{{
              item.name
            }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="部门分配" prop="departIds_str">
          <j-select-depart
            :disabled="isStatus == 'view'"
            style="width: 100%;"
            v-model="editForm.departIds_str"
            :multi="true"
            @back="backDepartInfo"
            :backDepart="true"
            :treeOpera="true"
          ></j-select-depart>
        </a-form-model-item>
      </a-form-model>
    </div>
    <div style="position: absolute;left: 50%;top: 50%;z-index: 998;">
      <a-spin :spinning="searchLoading" tip="loading" size="large" />
    </div>
    <Map ref="mapDrawId" style="height: 550px; background-color: #f7f7f7;" />
  </a-modal>
</template>

<script>
import * as api from '@/api/xlgc/areaEvent.js'
import * as videoApi from '@/api/xlgc/videoManage.js'
import Map from '@/views/xlgc/modules/map'
export default {
  props: ['visible', 'row', 'isStatus', 'title'],
  components: { Map },
  data() {
    return {
      pop: {
        title: '新增重点监控区域',
        isShow: false,
        loading: false,
        width: 1150
      },
      editForm: {
        sysAreaId: '',
        deviceIds: [],
        departIds: [],
        departIds_str: ''
      },
      rules: {
        sysAreaId: [{ required: true, message: '请选择', trigger: 'change' }],
        deviceIds: [{ required: true, message: '请选择', trigger: 'change' }],
        departIds_str: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      pageFilter: {
        pageNo: 1,
        pageSize: 10,
        regionType: 1 // 1正常2停用
      },
      cameraFilter: {
        pageNo: 1,
        pageSize: 10000
      },
      areaList: [],
      camerasList: [
        {
          id: '111',
          name: '侧门外监控'
        },
        {
          id: '222',
          name: '停车位监控'
        },
        {
          id: '333',
          name: '正大门外监控'
        }
      ],
      nextDepartOptions: [],
      searchLoading: false
    }
  },
  computed: {},
  watch: {
    visible(value) {
      if (value) {
        this.pop.loading = false
        this.getAreaList()
        this.$nextTick(() => {
          this.$refs.mapDrawId.clearAll()
          if (this.isStatus != 'add') {
            this.getDetail()
          }
        })
      }
    },
    title(value) {
      this.pop.title = value
    }
  },
  methods: {
    close() {
      this.$emit('on-close')
      return false
    },
    getAreaList() {
      this.loading = true
      api
        .getPageListByUnit(this.pageFilter)
        .then(res => {
          if (res.success) {
            this.areaList = res.result.records
            this.loading = false
          } else {
            this.loading = false
          }
        })
        .catch(e => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    onAreaChange(areaId) {
      console.log('areaId')
      console.log(areaId)
      this.getAreaDetail(areaId) // 获取框选区域
      this.getAreaCameras(areaId) // 获取摄像头
    },
    onCameraChange() {},
    getAreaDetail(id) {
      this.searchLoading = true
      api
        .getDetailsById({ id: id })
        .then(res => {
          if (res.success) {
            this.searchLoading = false
            let { chartVOList } = res.result
            this.$refs.mapDrawId.onChartVOList({ chartVOList })
          }
        })
        .catch(e => {
          this.$message.warn('请求失败！')
        })
    },
    getAreaCameras(id) {
      this.cameraFilter.sysAreaId = id
      videoApi
        .areaCameras(this.cameraFilter)
        .then(res => {
          if (res.success) {
            // this.camerasList = res.result.records
          }
        })
        .catch(e => {
          this.$message.warn('请求失败！')
        })
    },
    getDetail() {
      videoApi
        .areaDetail({ id: this.row.id })
        .then(res => {
          if (res.success) {
            let data = res.result
            // this.editForm.sysAreaId = data.areaId
            this.$set(this.editForm, 'sysAreaId', data.areaId)
            this.getAreaDetail(data.areaId) // 获取框选区域
            this.getAreaCameras(data.areaId) // 获取摄像头
            // 部门
            this.editForm.departIds_str = data.relationDeparts.join()
            // 所选的摄像头
            let arr = []
            data.relationCameras.forEach(item => {
              arr.push(item.id)
            })
            this.editForm.deviceIds = arr
          }
        })
        .catch(e => {
          this.$message.warn('请求失败！')
        })
    },
    onPopSubmit() {
      if (this.isStatus == 'view') {
        this.close()
        this.pop.loading = false
      } else {
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            this.pop.loading = true
            // console.log('11111111111')
            if (this.isStatus == 'edit') {
              // *********************** 摄像头相关**************************
              let arr1 = [0, 1, 2, 3, 4, 5] // 原来的
              let arr2 = [0, 1, 2, 6, 7, 8] // 提交的
              let dArr = this.getDifferent(arr1, arr2)
              // [3, 4, 5, 6, 7, 8] //不同的
              console.log('不同')
              console.log(dArr)
              let deviceIdsCanceled = this.getEqual(arr1, dArr) // 不同的和原来的相比，取相同的就是减少的
              // [3, 4, 5] //不同的
              console.log('相同，即时减少的')
              console.log(deviceIdsCanceled)
              let deviceIdsNewSelected = this.getDifferent(deviceIdsCanceled, dArr) // 不同的和原来的相比，取不相同的就是增加的
              // [6, 7, 8] //不同的
              console.log('不相同，即时增加的')
              console.log(deviceIdsNewSelected)
              // *********************** 部门相关**************************
              let departIdsCanceled = []
              let departIdsNewSelected = []

              let params = {
                cctvAreaId: this.row.id,
                sysAreaId: this.editForm.sysAreaId,
                deviceIdsCanceled: deviceIdsCanceled, // 取消监控设备ID列表
                deviceIdsNewSelected: deviceIdsNewSelected, // 新选择监控设备ID列表
                departIdsCanceled: departIdsCanceled, // 取消授权使用部门ID列表
                departIdsNewSelected: departIdsNewSelected // 新选择授权使用部门ID列表
              }
              // 修改
              videoApi
                .areaUpdate(params)
                .then(res => {
                  if (res.success) {
                    this.$message.success('修改成功！')
                    this.$emit('on-submit')
                    this.close()
                    this.pop.loading = false
                  } else {
                    this.pop.loading = false
                    this.$message.warning(res.message)
                  }
                })
                .catch(() => {
                  this.pop.loading = false
                  this.$forceUpdate()
                })
            } else {
              // 添加
              this.editForm.departIds = this.editForm.departIds_str.split(',')
              console.log(this.editForm)
              videoApi
                .areaAdd(this.editForm)
                .then(res => {
                  if (res.success) {
                    this.$message.success('添加成功！')
                    this.$emit('on-submit')
                    this.editForm.chartVOList = []
                    this.close()
                    this.pop.loading = false
                  } else {
                    this.pop.loading = false
                    this.$message.warning(res.message)
                  }
                })
                .catch(() => {
                  this.pop.loading = false
                  this.$forceUpdate()
                })
            }
          }
        })
      }
    },
    // 取出不同的元素
    getDifferent(arr1, arr2) {
      return arr1.concat(arr2).filter(function(v, i, arr) {
        return arr.indexOf(v) === arr.lastIndexOf(v)
      })
    },
    // 取出相同的元素
    getEqual(arr1, arr2) {
      let newArr = []
      for (let i = 0; i < arr2.length; i++) {
        for (let j = 0; j < arr1.length; j++) {
          if (arr1[j] === arr2[i]) {
            newArr.push(arr1[j])
          }
        }
      }
      return newArr
    },
    backDepartInfo(info) {
      // this.editForm.departIds = this.editForm.selecteddeparts
      this.nextDepartOptions = info.map((item, index, arr) => {
        let c = { label: item.text, value: item.value + '' }
        return c
      })
    }
  }
}
</script>
<style lang="less" scoped>
.ctr-box {
  // margin-bottom: 24px;
  .gutter-row {
    margin-bottom: 16px;
  }
  .r-clear {
    margin-top: 3px;
    // position: absolute;
    // right: 0;
    // margin-right: 30px;
    margin-left: 50px;
  }
}

.skpz-search-address {
  position: absolute;
  right: 27px;
  top: 147px;
  z-index: 999;
  width: 350px;
  .search-address-list {
    width: 302px;
    top: 38px;
    left: 0px;
    background-color: #fff;
    color: #aaa;
    font-size: 12px;
    height: 300px;
    overflow-y: scroll;
    .search-address-name {
      width: 100%;
      height: 30px;
      line-height: 30px;
      margin-left: 10px;
      border-bottom: 1px solid #d9d9d9;
      cursor: pointer;
    }
  }
}
/deep/.BMapLib_Drawing {
  // inset: 5px auto auto 5px !important;
  position: absolute !important;
  left: 5px !important;
  top: 5px !important;
}
.leftBox {
  overflow: hidden;
  position: absolute;
  left: 20px;
  top: 139px;
  height: 550px;
  width: 450px;
  .handle {
    position: absolute;
    display: inline-block;
    top: 0;
    z-index: 10;
    background: rgba(0, 0, 0, 0.6);
    height: 100%;
    cursor: pointer;
    transition: 0.5s;
    display: flex;
    flex-direction: column;
    justify-content: center;
    .close-icon {
      font-size: 20px;
      color: #fff;
    }
    &.leftHandle {
      left: 0;
    }
    &.rightHandle {
      right: 0;
    }
  }
}
/deep/.ant-form {
  display: flex;
  .ant-row {
    margin: 0;
    flex: 1;
  }
}
</style>
